package cn.fscode.code.generator.common.fieldbind;

import cn.fscode.commons.data.mate.fieldbind.inter.IDataBind;
import cn.fscode.commons.data.mate.fieldbind.model.DictType;
import cn.fscode.commons.data.mate.fieldbind.model.FieldBindAnnotationData;
import cn.fscode.commons.tool.core.reflection.MetaObject;
import cn.fscode.code.generator.model.po.SysDictItemPO;
import cn.fscode.code.generator.service.ISysDictItemService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 数据库字段字典绑定
 * @author shenguangyang
 */
@Component
public class SystemDictFieldBind implements IDataBind<Map<String, Map<String, SysDictItemPO>>> {
    private static final Map<String, SysDictItemPO> EMPTY_MAP = new HashMap<>();
    @Resource
    private ISysDictItemService sysDictItemService;

    @Override
    public Map<String, Map<String, SysDictItemPO>> getCodesOfTypes(List<DictType> dictTypes) {
        return sysDictItemService.listByCodes(dictTypes.stream().map(DictType::getType).collect(Collectors.toList()));
    }

    @Override
    public void setMetaObject(MetaObject metaObject, Map<String, Map<String, SysDictItemPO>> codesOfTypes,
                              Object fieldValue, FieldBindAnnotationData annotationData) {
        // 通过type或者对应的字典键值对, 然后通过 fieldValue = itemLabel, 或者对应的 itemValue
        Object value = this.assemblyTargetFieldValue(fieldValue, annotationData, code -> {
            SysDictItemPO data = Optional.ofNullable(codesOfTypes.get(String.valueOf(annotationData.getType())))
                    .orElse(EMPTY_MAP).get(String.valueOf(code));
            return Optional.ofNullable(data).map(SysDictItemPO::getItemLabel).orElse("");
        });
        metaObject.setValue(annotationData.getTarget(), value);
    }
}
